import React, { useRef, useState, useEffect } from 'react';
import type { FormProps } from 'antd';
import { Modal, Form, Input, Select, Radio, Upload, message } from 'antd';
import { ConsoleSqlOutlined, UploadOutlined } from '@ant-design/icons';
import type { RcFile } from 'antd/es/upload/interface';
import { apiInterceptors } from '@/client/api'
import { getRDBMSDataSourceList, getTableList } from '@/client/api/smartTable'
import { useRequest } from 'ahooks'
const { Dragger } = Upload;
const ImportData: React.FC<{ open: boolean, startImporting: () => void, cancelImport: () => void }> = ({ open, startImporting, cancelImport }) => {
  const [dataSource, setDataSource] = useState<Object[]>([])
  const [dataTable, setDataTable] = useState<Object[]>([])
  const [disabled, setDisabled] = useState(true);
  const [form] = Form.useForm();

  const [type, setImportType] = useState('1');
  const [fileList, setFileList] = useState([]);
  const [db_name, setDbname] = useState('');
  const excelMimeTypes = [
    'application/vnd.ms-excel', // .xls
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel.sheet.macroEnabled.12', // .xlsm
  ];
  useEffect(() => {
    getRDBMSDataSourceListRun()
  }, [])
  const handleOk = () => {
    form.validateFields()
      .then(values => {
        let data = values
        data['db_name'] = db_name
        startImporting(data); // 将值传递给父组件
      })
      .catch(errorInfo => {
        console.log('验证失败:', errorInfo);
      });
  };
  const handleCancel = () => {
    cancelImport()
  };

  type FieldType = {
    datasource_id?: string;
    table_name?: string;
    table_filter?: string;
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const onGenderChange = (e: any) => {
    const filteredData = dataSource.filter(item => item.id == e);
    setDbname(filteredData[0].params.database)
    getTableListRun(e)
  }
  const onSelectTble = () => {
    console.log('onSelectTble')
  }
  // 自定义上传逻辑
  const handleChange = async ({ file, onSuccess, onError }) => {
    onSuccess("ok");
  };
  const beforeUpload = (file: RcFile) => {
    if (!excelMimeTypes.includes(file.type)) {
      message.error('只能上传 Excel 文件（.xls, .xlsx, .xlsm）');
      return Upload.LIST_IGNORE;
    }
    return true;
  };
  const onChange = ({ fileList }) => {
    setFileList(fileList.slice(-1));
  };
  //获取数据源列表
  const { run: getRDBMSDataSourceListRun } = useRequest(
    async () => {
      return await getRDBMSDataSourceList()
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data || {}
        if (success == true) {
          setDataSource(data)
        }
      },

    }
  )
  //获取数据表列表
  const { run: getTableListRun } = useRequest(
    async (datasource_id) => {
      return await getTableList(datasource_id)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data || {}
        if (success == true) {
          setDataTable(data)
        }
      }
    }
  )
  return (
    <>
      <Modal
        title={
          <div
            style={{ width: '100%', cursor: 'move' }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
            onFocus={() => { }}
            onBlur={() => { }}
          >
            导入
          </div>
        }
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div>
          <Form
            name="basic"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            style={{ maxWidth: 640 }}
            initialValues={{ remember: true, type: '1' }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item label='' name='type'>

              <Radio.Group onChange={(e) => setImportType(e.target.value)}>

                <Radio value='1'>上传Excel</Radio>
                <Radio value='2'>从数据库导入</Radio>
              </Radio.Group>
            </Form.Item>

            {type === '1' && (
              <Form.Item label="" name="uploadImage" wrapperCol={{ span: 24 }} rules={[{ required: true, message: '请上传Excel文件' }]}>
                <Dragger
                  maxCount={1}
                  multiple={false}
                  beforeUpload={beforeUpload}
                  customRequest={handleChange}
                  fileList={fileList}
                  onChange={onChange}
                  accept=".xls,.xlsx,.xlsm"
                >
                  <p className="ant-upload-drag-icon">
                    <UploadOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文件上传</p>
                  {/* <p className="ant-upload-hint">支持单个或批量上传</p> */}
                </Dragger>
              </Form.Item>
            )}

            {type === '2' && (
              <>
                <Form.Item<FieldType> name="datasource_id" label="数据源" rules={[{ required: true, message: '请选择数据源' }]}>
                  <Select
                    onChange={onGenderChange}
                    allowClear
                    placeholder='请选择数据源'
                  >
                    {dataSource.map((node:any) => (
                      <Select.Option key={node.id} value={node.id}>{node && node.params && node.params.database}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item<FieldType> name='table_name' label='数据表' rules={[{ required: true, message: '请选择数据表' }]}>
                  <Select onChange={onSelectTble} allowClear placeholder='请选择数据表' showSearch filterOption={(input, option) =>
      (option?.value ?? '').toLowerCase().includes(input.toLowerCase())
    }>
                    {dataTable.map((item: any, index: Number) => (
                      <Select.Option key={item} value={item}>{item}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item<FieldType>
                  label="过滤条件"
                  name="table_filter"
                >
                  <Input.TextArea rows={6} placeholder="不需要写 where，只需要写where后面的内容" />
                </Form.Item>
              </>
            )}
          </Form>
        </div>
      </Modal>
    </>
  );
};

export default ImportData;